import { connect, mapProps } from '@formily/vue';
import { ElSwitch } from 'element-plus';
import { each, merge } from 'lodash-es';
import { Component, defineComponent, h } from 'vue';

export type SwitchProps = typeof ElSwitch;

export const transformComponent = <T extends Record<string, any>>(
  tag: any,
  transformRules?: Record<string, any>,
  defaultProps?: Partial<T>
): Component<T> | any => {
  return defineComponent({
    inheritAttrs: false,
    setup(props, { attrs, slots }) {
      return () => {
        let data = {
          ...attrs,
        };

        if (transformRules) {
          // data['onUpdate:modelValue'] = data['onChange'];
          // data['modelValue'] = data.defaultValue;
          const listeners = transformRules;
          each(listeners, (value, key) => {
            data[value] = data[key];
            delete data[key];
            // event = update:modelValue
            // extract = change
            // data[`on${event[0].toUpperCase()}${event.slice(1)}`] =
            //   attrs[`on${extract[0].toUpperCase()}${extract.slice(1)}`]
            // return false
            // data["onUpdate:modelValue"] = data["onChange"]
          });
        }

        if (defaultProps) {
          data = merge(defaultProps, attrs);
        }

        return h(tag, data, slots);
      };
    },
  });
};

const TransformElSwitch = transformComponent<SwitchProps>(ElSwitch, {
  change: 'update:modelValue',
  value: 'modelValue',
});

export const Switch = connect(
  TransformElSwitch,
  mapProps({
    value: 'modelValue',
    readOnly: 'readonly',
  })
);

export default Switch;
